/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import entities.Answer;
import entities.Question;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;

/**
 *
 * @author Оксана
 */
public class AnswerDaoImpl extends AbstractDao implements AnswerDao {
    
    @Autowired
    public AnswerDaoImpl(JdbcTemplate jdbcTemplate) {
        super(jdbcTemplate);
    }

    @Override
    public void create(Answer answer) {
        jdbcTemplate.update("insert into answers (id, text, letter, correct, question)"
                + " values (?, ?, ?, ?, ?)", answer.getId(), answer.getText(),
                answer.getLetter(), answer.isCorrect() ? 1 : 0, answer.getQuestion().getId());
    }

    @Override
    public Answer findById(Integer id) {
        return jdbcTemplate.queryForObject("select id, text, letter, correct, question"
                + " from answers where id = ?", new Object[] {id}, new AnswerMapper());
    }

    @Override
    public List<Answer> findByQuestionId(Integer questionId) {
        return jdbcTemplate.query("select id, text, letter, correct, question"
                + " from answers where question = ?", new Object[] {questionId}, 
                new AnswerMapper());
    }
    
    private final static class AnswerMapper implements RowMapper<Answer> {

        @Override
        public Answer mapRow(ResultSet rs, int i) throws SQLException {
            Answer answer = new Answer();
            answer.setId(rs.getInt("id"));
            answer.setText(rs.getString("text"));
            answer.setLetter(rs.getString("letter"));
            answer.setCorrect(rs.getInt("correct") == 1);
            Question question = new Question();
            question.setId(rs.getInt("question"));
            answer.setQuestion(question);
            return answer;                    
        }
    }
}
